package com.engine.workflow.xinri.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-05-10
 * @Description: 新日调用自定义流程接口
 * @ModifyLog:
 **/

public class WeaXinriWorkflowWeb extends BaseBean {

    /**
     * @Description: 流程更新
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/8/12
     */
    @POST
    @Path("/doUpdateRequest")
    @Produces({MediaType.TEXT_PLAIN})
    public String doUpdateRequest(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String requestid = Util.null2String(request.getParameter("requestid"));
        String mainData = Util.null2String(request.getParameter("mainData"));
        String detailData = Util.null2String(request.getParameter("detailData"));
        String approval = Util.null2String(request.getParameter("approval"));
        String RASUserid = Util.null2String(request.getHeader("userid"));
        String RASToken = Util.null2String(request.getHeader("token"));
        writeLog(">>>>>doUpdateRequest>>>requestid=" + requestid);
        writeLog(">>>>>doUpdateRequest>>>RASUserid=" + RASUserid);
        writeLog(">>>>>doUpdateRequest>>>RASToken=" + RASToken);
        WfUtil wfUtil = new WfUtil();
        try {
            Map<String, Object> tokenMap = wfUtil.checkToken(RASToken);
            String token_code = Util.null2String(tokenMap.get("code"));
            if ("SUCCESS".equals(token_code)) {
                Map<String, Object> useridMap = wfUtil.checkUserid(RASUserid);
                String userid_code = Util.null2String(useridMap.get("code"));
                if ("SUCCESS".equals(userid_code)) {
                    String userid = Util.null2String(useridMap.get("userid"));
                    Map<String, Object> requestidMap = wfUtil.checkRequestid(requestid);
                    String requestid_code = Util.null2String(requestidMap.get("code"));
                    if ("SUCCESS".equals(requestid_code)) {
                        String workflowId = Util.null2String(wfUtil.getWorkflowId(requestid));
                        writeLog(">>>>>doUpdateRequest>>>userid=" + userid);
                        String formid = wfUtil.getFormid(workflowId);
                        writeLog(">>>>>doUpdateRequest>>>workflowId=" + workflowId + ",formid=" + formid);
                        Map<String, Object> mainDataMap = wfUtil.checkMainData(mainData);
                        String mainData_code = Util.null2String(mainDataMap.get("code"));
                        if ("SUCCESS".equals(mainData_code)) {
                            JSONArray mainDatalist = JSONArray.parseArray(mainData);
                            Map<String, Object> mainMap = new HashMap<String, Object>();
                            for (int i = 0; i < mainDatalist.size(); i++) {
                                JSONObject mainFields = mainDatalist.getJSONObject(i);
                                String fieldName = Util.null2String(mainFields.getString("fieldName"));
                                String fieldValue = Util.null2String(mainFields.getString("fieldValue"));
                                mainMap.put(fieldName, fieldValue);
                            }
                            if (!"".equals(approval)) {
                                mainMap.put("thsfcxsp", approval);
                            }
                            String tableName = "formtable_main_" + formid;
                            writeLog(">>>>>doUpdateRequest>>>tableName=" + tableName);
                            boolean isUpdate = wfUtil.updateMainData(tableName, requestid, mainMap);
                            writeLog(">>>>>doUpdateRequest>>>isUpdate=" + isUpdate);
                            if (isUpdate) {
                                if (!"".equals(detailData)) {
                                    JSONArray detailDatalist = JSONArray.parseArray(detailData);
                                    String mainid = Util.null2String(wfUtil.getIdByRequestId(tableName, requestid));
                                    int dtlTableSumCount = detailDatalist.size();
                                    int dtlTableSuccCount = 0;
                                    for (int i = 0; i < detailDatalist.size(); i++) {
                                        JSONObject detailDatas = detailDatalist.getJSONObject(i);
                                        String dtltableName = Util.null2String(detailDatas.getString("tableDBName"));
                                        if (!"".equals(dtltableName)) {
                                            writeLog(">>>>>doUpdateRequest>>>detailData>>>>dtltableName=" + dtltableName);
                                            String tableRecords = Util.null2String(detailDatas.getString("workflowRequestTableRecords"));
                                            if (!"".equals(tableRecords)) {
                                                boolean isDelete = wfUtil.deleteDetailData(dtltableName, mainid);
                                                writeLog(">>>>>doUpdateRequest>>>isDelete=" + isDelete);
                                                JSONArray recordslist = JSONArray.parseArray(tableRecords);
                                                int sumCount = recordslist.size();
                                                int succCount = 0;
                                                for (int j = 0; j < recordslist.size(); j++) {
                                                    Map<String, Object> detailMap = new HashMap<String, Object>();
                                                    JSONObject records = recordslist.getJSONObject(j);
                                                    String recordOrder = Util.null2String(records.getString("recordOrder"));
                                                    writeLog("detailData>>>>recordOrder=" + recordOrder);
                                                    String tableFields = Util.null2String(records.getString("workflowRequestTableFields"));
                                                    if (!"".equals(tableFields)) {
                                                        JSONArray tableFieldslist = JSONArray.parseArray(tableFields);
                                                        for (int k = 0; k < tableFieldslist.size(); k++) {
                                                            JSONObject detailFields = tableFieldslist.getJSONObject(k);
                                                            String fieldName = Util.null2String(detailFields.getString("fieldName"));
                                                            String fieldValue = Util.null2String(detailFields.getString("fieldValue"));
                                                            detailMap.put(fieldName, fieldValue);
                                                        }
                                                        detailMap.put("mainid", mainid);
                                                        if (isDelete) {
                                                            boolean isDtlUpdate = wfUtil.updateDetailData(dtltableName, detailMap);
                                                            writeLog(">>>>>doUpdateRequest>>>isDtlUpdate=" + isDtlUpdate);
                                                            if (isDtlUpdate) {
                                                                succCount++;
                                                            }
                                                        }
                                                    }
                                                }
                                                if (succCount == sumCount) {
                                                    dtlTableSuccCount++;
                                                }
                                                writeLog(">>>>>doUpdateRequest>>>succCount=" + succCount + ",sumCount=" + sumCount);
                                            }
                                        }
                                    }
                                    writeLog(">>>>>doUpdateRequest>>>dtlTableSuccCount=" + dtlTableSuccCount + ",dtlTableSumCount=" + dtlTableSumCount);
                                    if (dtlTableSumCount == dtlTableSuccCount) {
                                        String submitMsg = wfUtil.submitWorkflow(Util.getIntValue(requestid), Util.getIntValue(userid));
                                        writeLog(">>>>>doUpdateRequest>>>submitMsg=" + submitMsg);
                                        if ("success".equals(submitMsg)) {
                                            apidatas.put("code", "SUCCESS");
                                            JSONObject dataJson = new JSONObject();
                                            dataJson.put("msg", "流程更新并提交成功");
                                            apidatas.put("data", dataJson);
                                            apidatas.put("errMsg", "");
                                        } else {
                                            apidatas.put("code", "NO_PERMISSION");
                                            JSONObject dataJson = new JSONObject();
                                            dataJson.put("msg", "人员" + userid + "流程无权限提交或者流程已归档");
                                            apidatas.put("data", dataJson);
                                            apidatas.put("errMsg", submitMsg);
                                        }

                                    } else {
                                        apidatas.put("code", "PARAM_ERROR");
                                        JSONObject dataJson = new JSONObject();
                                        dataJson.put("detailData", "请检查fieldName字段，fieldValue字段类型以及tableDBName表名是否存在");
                                        apidatas.put("data", dataJson);
                                        apidatas.put("errMsg", "detailData参数错误，明细表更新失败");
                                    }
                                } else {
                                    String submitMsg = wfUtil.submitWorkflow(Util.getIntValue(requestid), Util.getIntValue(userid));
                                    writeLog(">>>>>doUpdateRequest>>>submitMsg=" + submitMsg);
                                    if ("success".equals(submitMsg)) {
                                        apidatas.put("code", "SUCCESS");
                                        apidatas.put("data", "流程更新成功，提交成功");
                                        apidatas.put("errMsg", "");
                                    } else {
                                        apidatas.put("code", "NO_PERMISSION");
                                        apidatas.put("data", "流程更新成功，提交失败");
                                        apidatas.put("errMsg", submitMsg);
                                    }
                                }

                            } else {
                                apidatas.put("code", "PARAM_ERROR");
                                JSONObject dataJson = new JSONObject();
                                dataJson.put("mainData", "fieldName字段和单据字段不一致");
                                apidatas.put("data", dataJson);
                                apidatas.put("errMsg", "mainData参数错误，主表更新失败");
                            }

                        } else {
                            apidatas = mainDataMap;
                        }
                    } else {
                        apidatas = requestidMap;
                    }
                } else {
                    apidatas = useridMap;
                }
            } else {
                apidatas = tokenMap;
            }
            writeLog(">>>>>getPreviewTest>>>apidatas=" + apidatas.toString());
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("code", "SYSTEM_INNER_ERROR");
            JSONObject dataJson = new JSONObject();
            dataJson.put("error", "程序内部异常");
            apidatas.put("data", dataJson);
            apidatas.put("errMsg", "接口异常");
        }

        return JSONObject.toJSONString(apidatas);
    }


}
